import { defineStore } from 'pinia'
import { getVidoData } from '../api/search'
import { getshopData } from '../api/search'
import { getcollectionData } from '../api/search'
import { showNotify } from 'vant'

export const useSearchStore = defineStore('search', {
  state: () => ({
    videoResults: null,
    shopResults: null,
    collectionData: null,
    userId: JSON.parse(localStorage.getItem('userId') || '0'), // 示例用户 IDzzz
    sessionId: JSON.parse(localStorage.getItem('sessionId') || '0') // 示例会话 ID
  }),
  actions: {
    //获取视频
    async handleSearch(categoryId: string, page: number, count: number) {
      try {
        const videoData = await getVidoData({ categoryId, page, count })
        console.log('videoData', videoData)

        // 安全地访问数据，假设正确结构是 videoData.data.results
        this.$state.videoResults = videoData.data.result || []
        console.log('视频', this.$state.videoResults)
      } catch (error) {
        console.error('获取视频数据失败:', error)
      }
    },
    //购买视频
    async shopdata(videoId: number, price: number) {
      try {
        const { userId, sessionId } = await useSearchStore()
        const shopData = await getshopData(userId, sessionId, { videoId, price })
        console.log(shopData, '视频购买')

        // 假设后端返回的数据结构是 { code: 200, data: { message: 'Success' } }
        if (shopData && shopData.data.code === 200) {
          this.$state.shopResults = shopData.data.message
          console.log(this.$state.shopResults, 'shipin')
        } else {
          console.error('购买视频失败:', shopData.data.message)
        }
      } catch (error) {
        console.error('购买视频失败:', error)
      }
    },
    //收藏
    async handshouData(videoId: number) {
      try {
        const { userId, sessionId } = await useSearchStore()
        const shopData = await getcollectionData(userId, sessionId, { videoId })
        console.log(shopData, '收藏视频')
        showNotify({ type: 'success', message: '视频收藏成功' })
      } catch (error) {
        showNotify({ type: 'danger', message: '视频收藏失败' })
      }
    }
  }
})
